﻿using SetSailCommon;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SetSailDal;
using SetSailModel;
using SetSailControl;
using System.Diagnostics;

namespace SetSailView
{
    public partial class Frm_Login : Form
    {
        private string _version;
        private string _newversion;
        public Frm_Login()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体重绘（圆角）
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            RenderHelper.SetFormRoundRectRgn(this, 30);
        }

        //window标准拖拽事件
        [DllImport("user32.dll", EntryPoint = "ReleaseCapture")]
        public static extern void ReleaseCapture();
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern void SendMessage(int hwnd, int wMsg, int wParam, int lParam);

        private void Frm_Login_Load(object sender, EventArgs e)
        {
            //开窗出事位置
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(SystemInformation.PrimaryMonitorSize.Width / 2 - 333, SystemInformation.PrimaryMonitorSize.Height / 2 - 208);

            //获取字典管理
            ResultModel<List<Cookie_ZD>> result = LoginDal.GetCookieInfo();
            if (result.Code == ResultCode.Success)
            {
                CookieData.getInstance().ZDGL = result.Data;
                //读档类型
                List<Cookie_ZD> ls = CookieData.getInstance().ZDGL.Where(a => a.ZDDM == "CDDLX").ToList();
                TxtDDLX.Source = CommonHelper.ComDataSource(ls);
                TxtDDLX.SelectedIndex = 0;
            }
            else
            {
                MessShow.ShowMistake(result.Message);
            }

            //注册账号添加正则
            Cookie_ZD zd = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "DLMM").FirstOrDefault();
            if (zd != null)
            {
                verificationComponent1.SetVerificationCustomRegex(TxtZCZH, zd.MXZ);
            }

            //记住密码
            bool is_save = Convert.ToBoolean(SetSailReadFileTools.Properties.Settings.Default.IsSavePwd);
            string UserName = Convert.ToString(SetSailReadFileTools.Properties.Settings.Default.UserName);
            string Password = Convert.ToString(SetSailReadFileTools.Properties.Settings.Default.Password);
            //赋值默认值
            IsSavePwd.Checked = is_save;
            TxtZH.InputText = UserName.Trim();
            TxtMM.InputText = Password.Trim();



            //获取版本号
            _version = Application.ProductVersion;
            _newversion = CookieData.getInstance().ZDGL.Where(obj => obj.MXDM == "v").FirstOrDefault().MXZ.ToString();

            LbVersion.Text = "版本号：" + _version;
        }

        /// <summary>
        /// 窗体拖拽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage((int)this.Handle, 0xA1, 2, 0);
                //Console.WriteLine(ActionServo1.Location.X+"--"+ ActionServo1.Location.Y);
            }
        }

        /// <summary>
        /// 关闭、最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucNavigationMenu1_ClickItemed(object sender, EventArgs e)
        {
            if (ucNavigationMenu1.SelectItem != null)
            {
                switch (ucNavigationMenu1.SelectItem.TipText.Trim())
                {
                    case "关闭":
                        Application.ExitThread();
                        break;
                    case "最小化":
                        this.WindowState = FormWindowState.Minimized;
                        break;
                }
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtZH.InputText.Trim()))
            {
                MessShow.ShowHint("请输入账号");
                return;
            }

            if (string.IsNullOrWhiteSpace(TxtMM.InputText.Trim()))
            {
                MessShow.ShowHint("请输入密码");
                return;
            }
            string zh = TxtZH.InputText.Trim();
            string mm = CommonHelper.MD5Encrypt(TxtMM.InputText).Trim();

            var result = LoginDal.Login(zh, mm);
            if (result.Code == ResultCode.Success)
            {
                SavePwd();
                CookieData.getInstance().YHXX = result.Data;
                this.Hide();
                Frm_Main m = new Frm_Main();
                m.Show();
            }
            else
            {
                MessShow.ShowHint(result.Message);
                return;
            }
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt2_BtnClick(object sender, EventArgs e)
        {
            bool flag = verificationComponent1.Verification();
            if (flag)
            {
                if (TxtZCMM.InputText != TxtQRMM.InputText)
                {
                    MessShow.ShowHint("两次密码输入不一致");
                    return;
                }

                QH_ZCSH zcsh = new QH_ZCSH();
                zcsh.ID = CommonHelper.GetNewGuid();
                zcsh.ZCZH = TxtZCZH.InputText.Trim();
                zcsh.ZCMM = CommonHelper.MD5Encrypt(TxtZCMM.InputText).Trim();
                zcsh.DDLX = TxtDDLX.SelectedText.Trim();
                zcsh.SHZT = "待审核";
                var result = LoginDal.ADD_ZCSH(zcsh);
                if (result.Code == ResultCode.Success)
                {
                    TxtZCZH.InputText = "";
                    TxtZCMM.InputText = "";
                    TxtQRMM.InputText = "";
                    MessShow.ShowSure("已提交！请等待管理员审核");
                }
                else if (result.Code == ResultCode.Fail)
                    MessShow.ShowHint(result.Message);
                else
                    MessShow.ShowMistake(result.Message);
            }
        }

        /// <summary>
        /// 记住密码
        /// </summary>
        private void SavePwd()
        {
            if (IsSavePwd.Checked)
            {
                SetSailReadFileTools.Properties.Settings.Default.IsSavePwd = true;
                SetSailReadFileTools.Properties.Settings.Default.UserName = TxtZH.InputText.Trim();
                SetSailReadFileTools.Properties.Settings.Default.Password = TxtMM.InputText.Trim();
            }
            else
            {
                SetSailReadFileTools.Properties.Settings.Default.IsSavePwd = false;
                SetSailReadFileTools.Properties.Settings.Default.UserName = TxtZH.InputText.Trim();
                SetSailReadFileTools.Properties.Settings.Default.Password = string.Empty;
            }
            SetSailReadFileTools.Properties.Settings.Default.Save();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //判断数据库版本号和当前程序版本号是否一致
            //若不一致，开窗提示有新版本是否升级，不升级直接退出程序
            //如果点确定升级，根据数据库版本号获取文件存储压缩包放到当前程序中，下载完成之后结束当前程序启动SetSailUpgrade.exe
            //启动SetSailUpgrade.exe之后执行cmd名称覆盖安装，安装成功之后结束当前程序启动SetSailView.exe
            if (_version != _newversion)
            {
                timer1.Enabled = false;
                //MessShow.ShowHint(Environment.CurrentDirectory);
                DialogResult dialog = MessShow.ShowQuery("检测到有新版本是否升级");
                if (dialog == DialogResult.OK)
                {
                    ControlHelper.ThreadRunExt(this, () =>
                    {
                        CosHelper helper = new CosHelper();
                        helper.TransferDownloadObject(Environment.CurrentDirectory, "setup.zip", "setup/setup.zip").Wait();
                        ControlHelper.ThreadInvokerControl(this, () =>
                        {
                            if (helper.result2 != "ok")
                            {
                                Application.Exit();
                            }
                            else
                            {
                                Application.Exit();
                                ProcessStartInfo psi = new ProcessStartInfo();

                                psi.FileName = Environment.CurrentDirectory + @"\" + "SetSailUpgrade.exe";
                                psi.UseShellExecute = false;
                                psi.WorkingDirectory = Environment.CurrentDirectory;
                                psi.CreateNoWindow = true;
                                Process.Start(psi);
                                Process.GetCurrentProcess().Kill();
                            }
                        });
                    }, null, this);
                }
                else
                {
                    Application.Exit();
                }
            }
        }
    }
}
